package com.shangma.cn.exception;

import com.shangma.cn.commons.http.AxiosResult;
import com.shangma.cn.commons.http.AxiosStatus;
import com.shangma.cn.exception.base.impl.CustomerFormValidException;
import com.shangma.cn.exception.base.impl.ApiException;
import com.shangma.cn.exception.base.impl.UploadException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;

/**
 * 开发人员: 辉哥真球帅
 * 联系方式: zhengzhoudaxuevip@163.com
 * 创建时间: 2021/10/9  16:29
 * 文件含义:
 */
@RestControllerAdvice
public class GlobalExceptionHandlerAdvice {


    /**
     * 全局处理表单校验异常
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public AxiosResult<Void> formValidExceptionHandler(MethodArgumentNotValidException e) {
        BindingResult bindingResult = e.getBindingResult();
        if (bindingResult.hasErrors()) {
            List<FieldError> fieldErrors = bindingResult.getFieldErrors();
            FieldError fieldError1 = fieldErrors.get(0);
            AxiosStatus fromUnvalid = AxiosStatus.FROM_UNVALID;
            fromUnvalid.setMsg(fieldError1.getField() + fieldError1.getDefaultMessage());
            return AxiosResult.error(fromUnvalid);
        }
        AxiosStatus fromUnvalid = AxiosStatus.FROM_UNVALID;
        fromUnvalid.setMsg("表单校验失败");
        return AxiosResult.error(fromUnvalid);
    }


    /**
     * 处理自定义表单校验
     */

    @ExceptionHandler(CustomerFormValidException.class)
    public AxiosResult<Void> handlerCustomerExceptionHandler(CustomerFormValidException e) {
        return AxiosResult.error(e.getAxiosStatus());
    }


    /**
     * 文件上传异常
     */


    @ExceptionHandler(UploadException.class)
    public AxiosResult<Void> uploadException(UploadException uploadException) {
        return AxiosResult.error(uploadException.getAxiosStatus());
    }

    @ExceptionHandler(ApiException.class)
    public AxiosResult<Void> apiException(ApiException e) {
        return AxiosResult.error(e.getAxiosStatus());
    }

    /**
     * 处理未知异常
     */
    @ExceptionHandler(Exception.class)
    public AxiosResult<Void> handlerOtherException(Exception e) {
        AxiosStatus axiosStatus = AxiosStatus.XXXXX_EXCETION;
        axiosStatus.setMsg(e.toString());
        return AxiosResult.error(axiosStatus);
    }


}
